<template>
  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="40%" align-center>
    <ElTabs v-model="activeTab" type="border-card">
      <!-- 基础信息页签 -->
      <ElTabPane label="基础信息" name="basic">
        <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
          <ElRow :gutter="20">
            <ElCol :span="12">
              <ElFormItem label="规则编码" prop="rule_code">
                <ElInput v-model="formData.rule_code" placeholder="请输入规则编码" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="12">
              <ElFormItem label="规则名称" prop="name">
                <ElInput v-model="formData.name" placeholder="请输入规则名称" />
              </ElFormItem>
            </ElCol>
          </ElRow>

          <ElRow :gutter="20">
            <ElCol :span="12">
              <ElFormItem label="表名" prop="table_name">
                <ElSelect v-model="formData.table_name" placeholder="请选择表名" style="width: 100%" filterable
                  :loading="tableLoading" value-key="value" @change="handleTableChange">
                  <ElOption v-for="table in tableOptions" :key="table.value" :label="table.label"
                    :value="table.value" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="12">
              <ElFormItem label="条件类型" prop="condition_type">
                <ElSelect v-model="formData.condition_type" placeholder="请选择条件类型" style="width: 100%"
                  @change="handleConditionTypeChange">
                  <ElOption v-for="option in conditionTypeOptions" :label="option.label" :value="option.value" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="12">
              <ElFormItem label="操作方式" prop="logical_operator">
                <ElSelect v-model="formData.logical_operator" placeholder="请选择操作方式" style="width: 100%">
                  <ElOption label="AND" value="AND" />
                  <ElOption label="OR" value="OR" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
          </ElRow>

          <ElRow :gutter="20">
            <ElCol :span="12">
              <ElFormItem label="状态" prop="status">
                <ElRadioGroup v-model="formData.status">
                  <ElRadio :label="true">启用</ElRadio>
                  <ElRadio :label="false">禁用</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
          </ElRow>

          <ElFormItem label="描述" prop="description">
            <ElInput v-model="formData.description" type="textarea" :rows="3" placeholder="请输入描述" />
          </ElFormItem>
        </ElForm>
      </ElTabPane>

      <!-- 权限配置页签 -->
      <ElTabPane label="权限配置" name="config" :disabled="!formData.condition_type">
        <div v-if="!formData.condition_type" class="config-placeholder">
          <ElEmpty description="请先在基础信息中选择条件类型" />
        </div>
        <div v-else>
          <EnhancedPermissionForm :condition-type="formData.condition_type" :table-name="formData.table_name"
            v-model="formData.config_json" />
        </div>
      </ElTabPane>
    </ElTabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-ripple>提交</el-button>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { type FormInstance, type FormRules } from 'element-plus'
import { createDataPermissionRule, updateDataPermissionRule, DataPermissionRuleResponse } from '@/api/system/data-permission'
import { fetchAllTables, type TableOptionInfo } from '@/api/system/table'
import EnhancedPermissionForm from '@/components/EnhancedPermissionForm.vue'
import { useDictStore } from '@/store/modules/dict'
import { useSystemStore } from '@/store/modules/system'


interface Props {
  visible: boolean
  type: 'add' | 'edit'
  editData?: Partial<DataPermissionRuleResponse>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const system = useSystemStore()
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const dictStore = useDictStore()
const conditionTypeOptions = computed(() => dictStore.getOptions('condition_type') || [])
const roleOptions = computed(() => system.getRoles)

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const dialogTitle = computed(() => (props.type === 'add' ? '添加数据权限规则' : '编辑数据权限规则'))

// 页签状态
const activeTab = ref('basic')

// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  name: '',
  rule_code: '',
  table_name: '',
  condition_type: 'field_match',
  logical_operator: 'OR',
  config_json: {},
  description: '',
  status: true
})

// 表选项数据
const tableOptions = ref<TableOptionInfo[]>([])
const tableLoading = ref(false)

// 加载所有表
const loadAllTables = async () => {
  if (tableLoading.value) return

  try {
    tableLoading.value = true
    const data = await fetchAllTables()
    if (Array.isArray(data)) {
      tableOptions.value = data
    }
  } catch (error) {
    console.error('加载表列表失败:', error)
    ElMessage.error('加载表列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 校验规则
const rules: FormRules = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  rule_code: [{ required: true, message: '请输入规则编码', trigger: 'blur' }],
  table_name: [{ required: true, message: '请输入表名', trigger: 'blur' }],
  condition_type: [{ required: true, message: '请选择条件类型', trigger: 'change' }],
  config_json: [{ required: true, message: '请输入配置信息', trigger: 'blur' }]
}

// 初始化表单
const initFormData = () => {
  const isEdit = props.type === 'edit' && props.editData
  const row = props.editData || {}
  Object.assign(formData, {
    name: isEdit ? (row.name || '') : '',
    rule_code: isEdit ? (row.rule_code || '') : '',
    table_name: isEdit ? (row.table_name || '') : '',
    condition_type: isEdit ? (row.condition_type || 'field_match') : 'field_match',
    logical_operator: isEdit ? (row.logical_operator || 'OR') : 'OR',
    config_json: isEdit ? { ...(row.config_json || {}) } : {},
    description: isEdit ? (row.description || '') : '',
    status: isEdit ? (row.status ?? true) : true
  })
}

// 处理条件类型变化
const handleConditionTypeChange = () => {
  // 清空配置信息，让动态表单重新初始化
  formData.config_json = {}
  // 切换到配置页签
  if (formData.condition_type) {
    activeTab.value = 'config'
  }
}

// 处理表变化
const handleTableChange = () => {
  // 表变化时清空配置，因为字段选项会改变
  formData.config_json = {}
}



watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      nextTick(async () => {
        initFormData()
        // 重置页签到基础信息
        activeTab.value = 'basic'
        // 弹窗打开时加载表格列表
        await loadAllTables()
        formRef.value?.clearValidate()
      })
    }
  },
  { immediate: true }
)

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return

    // 验证配置信息
    if (!formData.config_json || Object.keys(formData.config_json).length === 0) {
      ElMessage.error('请完善配置信息')
      return
    }

    const payload = {
      name: formData.name,
      rule_code: formData.rule_code,
      table_name: formData.table_name,
      condition_type: formData.condition_type,
      logical_operator: formData.logical_operator,
      config_json: formData.config_json,
      description: formData.description || null,
      status: formData.status
    }

    try {
      if (props.type === 'add') {
        await createDataPermissionRule(payload)
      } else {
        const id = Number(props.editData?.id)
        if (!id) {
          ElMessage.error('缺少数据权限规则ID，无法编辑')
          return
        }
        await updateDataPermissionRule(id, payload)
      }
      ElMessage.success('提交成功')
      emit('submit')
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.config-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>
